package com.woniu.intlet.timer;

import com.alibaba.fastjson.JSON;
import com.woniu.outlet.dao.ProPlanPoMapper;
import com.woniu.outlet.dao.ProSchedulingPoMapper;
import com.woniu.outlet.po.ProPlanPo;
import com.woniu.outlet.po.ProPlanPoExample;
import com.woniu.outlet.po.ProSchedulingPo;
import com.woniu.outlet.po.ProSchedulingPoExample;
import com.woniu.service.ProPlanPoService;
import com.woniu.uitl.ProPlanStatus;
import com.woniu.uitl.ProScheduingStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class proPlanStatusTimer {

    @Autowired
    private ProPlanPoMapper proPlanPoMapper;
    @Autowired
    private ProSchedulingPoMapper proSchedulingPoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Scheduled(fixedRate = 30000)
    public void changeProPlan(){
        //查询所有不是已经完成的生产计划单
        ProPlanPoExample proPlanPoExample = new ProPlanPoExample();
        ProPlanPoExample.Criteria criteria = proPlanPoExample.createCriteria();
        criteria.andStatusNotEqualTo(ProPlanStatus.COMPLETE.getStatus());
        List<ProPlanPo> poList = proPlanPoMapper.selectByExample(proPlanPoExample);
        //没有生产计划单则return;
        if (poList.size() == 0){
            return;
        }
        for (ProPlanPo proPlanPo : poList) {
            //查询每个生产计划下的排程集合是否全部都已经完成
            ProSchedulingPoExample poExample = new ProSchedulingPoExample();
            ProSchedulingPoExample.Criteria cc = poExample.createCriteria();
            cc.andProPlanIdEqualTo(proPlanPo.getPlanNo());
            List<ProSchedulingPo> schedulingPos = proSchedulingPoMapper.selectByExample(poExample);
            //该生产计划下没有生产排程return;
            if (schedulingPos.size() == 0){
                return;
            }
            //定义计数器
            int count = 0;
            for (ProSchedulingPo schedulingPo : schedulingPos) {
                if (!schedulingPo.getStatus().equals(ProScheduingStatus.COMPLETE.getStatus())){
                    count++;
                }
            }
            //如果该生产计划下的所有生产排程全部完成,那么该生产计划也完成,相应的订单状态也完成
            if (count == 0){
                proPlanPo.setStatus(ProPlanStatus.COMPLETE.getStatus());
                proPlanPoMapper.updateByPrimaryKeySelective(proPlanPo);

                //将完成的生产计划单存入redis
                ValueOperations<String, String> ops = redisTemplate.opsForValue();
                ops.set(proPlanPo.getId().toString(),JSON.toJSONString(proPlanPo),2,TimeUnit.DAYS);
            }
        }

    }
}
